const { getUserInfo } = require('../service/user.service')
const bcrypt = require('bcryptjs')
const { userFormateError, invalidPassword, userLoginError, userDoesNotExist, userAlreadyExisted, userRegisterError } = require('../constant/err.type')
const userValidator = async (ctx, next) => {

    const { user_name, password } = ctx.request.body
    if (!user_name || !password) {
        console.error('用户名或密码为空', ctx.request.body)
        ctx.app.emit('error', userFormateError, ctx)
        return
    }
    await next()
}

const verifyUser = async (ctx, next) => {
    const { user_name } = ctx.request.body
    // 合理性
    try {
        const res = await getUserInfo({ user_name })
        // console.log(res);
        if (res) {
            console.error('用户名已存在123a', { user_name });
            ctx.app.emit('error', userAlreadyExisted, ctx)
            return
        }

    } catch (error) {
        ctx.app.emit('error', userRegisterError, ctx)
        return
    }
    await next()

}

const verifyLogin = async (ctx, next) => {
    // 1.判断用户是否存在(不存在报错)

    try {

        const { user_name, password } = ctx.request.body
        const res = await getUserInfo({ user_name })
        if (!res) {
            console.error('用户名不存在', { user_name })
            ctx.app.emit('error', userDoesNotExist, ctx)
            return
        }
        // 2.密码是否匹配(不匹配报错)
        if (!bcrypt.compareSync(password, res.password)) {
            console.error('密码错误')
            ctx.app.emit('error', invalidPassword, ctx)
            return
        }
    } catch (error) {
        console.error(error)
        return ctx.app.emit('error', userLoginError, ctx)
    }
    await next()

}
//密码加密
const cryptPassword = async (ctx, next) => {

    const { password } = ctx.request.body
    const salt = bcrypt.genSaltSync(10);
    // hash保存的是密文
    const hash = bcrypt.hashSync(password, salt);

    ctx.request.body.password = hash

    await next()
}
const cd = async (ctx, next) => {
    // 判断修改前和修改后密码是否一致
    const { password } = ctx.request.body  //输入的修改密码
    const id = ctx.state.user.id
    // console.log(ctx.state.user.id);
    const a = await getUserInfo({ id })
    if (bcrypt.compareSync(password, a.password)) {
        //密码相同
        //提示  密码相同，修改密码失败
        console.log('999');
        return ctx.body = {
            code: '001',
            message: '新密码和旧密码相同，修改密码失败',
            result: ''
        }

    }
    await next()
}

module.exports = {
    userValidator,
    verifyUser,
    cryptPassword,
    verifyLogin,
    cd
}